/**	
 *  This code is part of DNSpenTest (a project of sourceforge.net) and has 
 *  been developed by the Project's members.
 *    
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  
 */
package net.biaji.android.cmwrap.services;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import net.biaji.android.cmwrap.Config;
import net.biaji.android.cmwrap.Logger;
import net.biaji.android.cmwrap.utils.Utils;

public class DNSServer2 implements WrapServer {
	
	private final String TAG = "DNSServer2";
	private DatagramSocket serverS;
	private DatagramPacket packet;
	private AnalizeDNS rq;
	private int srvPort = 7442;
	private String originalDNS;
	
    private final String[] iptablesRules = new String[] {	
    		"iptables -t nat -%3$s OUTPUT %1$s -p udp --dport 53  -j DNAT  --to-destination 127.0.0.1:7442"
    };
    
    public DNSServer2() {
//    	originalDNS = Utils.getOriginalDNS();
//    	Utils.flushDns("127.0.0.1");
    	try {
			serverS = new DatagramSocket(srvPort, InetAddress.getByName("127.0.0.1"));
		} catch (SocketException e) {
            Logger.e(TAG, "DNSServer初始化错误，端口号" + srvPort, e);
        } catch (UnknownHostException e) {
            Logger.e(TAG, "DNSServer初始化错误，端口号" + srvPort, e);
        }
    }
		
	private DatagramPacket create_poisoned_pck () {
		rq.poisoner();
		DatagramPacket packet_out = new DatagramPacket(new byte[rq.getpayloadLenght() + 62], rq.getpayloadLenght() + 62);
		packet_out.setAddress(packet.getAddress());
		packet_out.setPort(packet.getPort());
		packet_out.setData(rq.getpayload_FORGED());
		return packet_out;
	}
	
	private void send_packet (DatagramPacket pck){
		try {
			serverS.send(pck);
			Logger.d(TAG, "POISONED...");
		} catch (IOException e) {
			e.printStackTrace();
		}
//		serverS.close();
	}
	
	private void receiveANDanswer (int port, String ip_server, String ip_h2h) {
//		serverS = null;
		packet = new DatagramPacket(new byte[512], 512);
		Logger.d(TAG, "wait for request on " + port + "/UDP port...");
		boolean isClose = false;
		while (true) {
//			try {
//				serverS = new DatagramSocket(port);
//			} catch (SocketException e) {
//				e.printStackTrace();
//			}
			try {
				serverS.receive(packet);
			} catch (SocketException e) {
				isClose = true;
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (isClose) return;
			rq = new AnalizeDNS(packet, ip_h2h);
			rq.parser();
			Logger.d(TAG, "Received data from: "
					+ packet.getAddress().toString().substring(1) + ":" + packet.getPort()
					+ " with length: " + packet.getLength() + " asking for: "
					+ String.valueOf(rq.getURL()));
//			System.out.print(rq.getURL());
//			System.out.print("\n");
			send_packet (create_poisoned_pck());
		}
	}

	@Override
	public void run() {
		receiveANDanswer(srvPort, "192.168.42.12", "23.226.224.34");
	}

	@Override
	public boolean isClosed() {
		return serverS.isClosed();
	}

	@Override
	public void close() throws IOException {
//		Utils.flushDns(originalDNS);
		serverS.close();
	}

	@Override
	public int getServPort() {
		return srvPort;
	}

	@Override
	public void setProxyHost(String host) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setProxyPort(int port) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setTarget(String target) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String[] getRules() {
		return iptablesRules;
	}
}
